package com.healthfitness.floating

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import com.healthfitness.floating.service.FloatingService

class MyApplication : Application() {
    private var activityCount = 0

    override fun onCreate() {
        super.onCreate()

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityStarted(activity: Activity) {
                if(activityCount ==0){
                    onAppForeground()
                }
                activityCount++
            }

            override fun onActivityStopped(activity: Activity) {
                activityCount--
                if (activityCount == 0) {
                    // 应用进入后台
                    onAppBackgrounded()
                }
            }

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })
    }

    private fun onAppBackgrounded() {
        startService(Intent(this, FloatingService::class.java))
    }

    private fun onAppForeground(){
        stopService(Intent(this, FloatingService::class.java))
    }
}